import React, { useState } from 'react'
import { Card, Form, Input, Button, Checkbox, message } from 'antd'
import logo from '@/assets/logo.png'
import style from './index.module.scss'
import { useDispatch } from 'react-redux'
import { login } from '@/store/actions/login'
import { useHistory, useLocation } from 'react-router'
export default function Login() {
  const dispatch = useDispatch()
  const history = useHistory()
  const location = useLocation()
  const [loading, setLoading] = useState(false)
  // const from = location.state
  // 提交表单
  const onFinish = async (values) => {
    setLoading(true)
    // 提交表单的时候发请求
    // 优化
    try {
      await dispatch(login(values))
      message.success('登录成功', 1, () => {
        const from = location.state ? location.state.from : '/home'
        history.replace(from)
      })
    } catch (e) {
      if (e.response) {
        message.error('登录失败')
      }

      setLoading(false)
    }
  }
  return (
    <div className={style.root}>
      <Card className="login-container">
        <img className="login-logo" src={logo} alt="" />
        <Form
          onFinish={onFinish}
          size="large"
          autoComplete="off"
          validateTrigger={['onChange', 'onBlur']}
          initialValues={{
            mobile: '13911111111',
            code: '246810',
            agreement: true,
          }}
        >
          <Form.Item
            name="mobile"
            rules={[
              { required: true, message: '手机号不能为空' },
              { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' },
            ]}
          >
            <Input placeholder="请输入手机号" />
          </Form.Item>

          <Form.Item
            name="code"
            rules={[
              { required: true, message: '验证码不能为空' },
              { pattern: /^\d{6}$/, message: '验证码格式错误' },
            ]}
          >
            <Input placeholder="请输入验证码" />
          </Form.Item>

          <Form.Item
            name="agreement"
            valuePropName="checked"
            rules={[
              {
                validator: (_, value) => {
                  return value
                    ? Promise.resolve()
                    : Promise.reject(new Error('请先阅读此条款'))
                },
              },
            ]}
          >
            <Checkbox>请同意并阅读此提款协议</Checkbox>
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" block loading={loading}>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}
